
WINDOW_ACTIVE = true;

$(document).ready(function(){
    // Kiem tra neu current window is active
    var interval_id;
    if(CORE.isLogin){
        $(window).focus(function() {
            WINDOW_ACTIVE = true;
            if(!PROCESS_AJAX){
                PROCESS_AJAX = setInterval(function(){$.process();},1000);
            }
        });

        $(window).blur(function() {
            WINDOW_ACTIVE = false;
            clearInterval(PROCESS_AJAX);
            PROCESS_AJAX = 0;
        });
    }
    $(document).click(function(){
        $('.main_menu_area').hide();
        $('.notification_panel').hide();
    });
    $('#quick_view_form').draggable();
    // Hien thi popup detail cua san pham
    CURRENT_PRODUCT = null;
    $('.product_content').on('click','.link_button',function(event){
        CURRENT_PRODUCT = $(this).closest('.item');
        if(event.which != 2){
            checkNextPreProduct();  
            $('.quick_view_loading').show();
            var new_top = ($(window).height() - $('#quick_view_form').height()) / 2;
            var new_left = ($(window).width() - $('#quick_view_form').width()) / 2;
            $('#quick_view_form').css({'top' : new_top + 'px' , 'left' : new_left + 'px',});
            $('#quick_view_form .content_form').html('');
            $('#quick_view_form').fadeIn();
            $('.popup_bg').fadeIn();
            ISCLOSE = false;
            var uri = $(this).attr('href');
            $.post('~product/quickViewProduct',{ uri : uri },function(data){  
                $('#quick_view_form .content_form').html(data);
                $('#quick_view_form .content_form img').load(function(){
                    $('.quick_view_loading').fadeOut(1000);
                });
            });
            event.preventDefault();
            return false;
        }
    });

    function checkNextPreProduct(){
        if(CURRENT_PRODUCT.next('.item').length > 0){
            $('.next_product_view').show();
        }
        else{
            $('.next_product_view').hide();
        }

        if(CURRENT_PRODUCT.prev('.item').length > 0){
            $('.pre_product_view').show();
        }
        else{
            $('.pre_product_view').hide();
        }
    }
    // Close form quick view
    $('#quick_view_form .close_quick_view_form').click(function(){
        ISCLOSE = true;
        $('#quick_view_form').fadeOut();
        $('.popup_bg').fadeOut();
        $('.message_area').removeClass('on_top');
    });

    // Next product view
    $('.next_product_view').click(function(){
        var next_product = CURRENT_PRODUCT.next('.item');
        if(next_product.length > 0){
            CURRENT_PRODUCT = next_product;
            var window_width = $(window).width();
            var new_top = ($(window).height() - $('#quick_view_form').height()) / 2;
            var new_left = ($(window).width() - $('#quick_view_form').width()) / 2;
            $('#quick_view_form').animate({'left' :(window_width + 60) + 'px'},500,function(){
                checkNextPreProduct();  
                $('.quick_view_loading').show();
                // Load next product
                var uri = CURRENT_PRODUCT.attr('val');
                $.post('~product/quickViewProduct',{ uri : uri },function(data){  
                    $('#quick_view_form .content_form').html(data);
                    $('#quick_view_form .content_form img').load(function(){
                        $('.quick_view_loading').fadeOut(1000);
                    });
                });
                $('#quick_view_form').css({'top' : (- $('#quick_view_form').height() -20) + 'px', 'left' : new_left + 'px'});
                $('#quick_view_form').animate({'top' : new_top + 'px'});
            });
        }
    });
    $('.pre_product_view').click(function(){
        var pre_product = CURRENT_PRODUCT.prev('.item');
        if(pre_product.length > 0){
            CURRENT_PRODUCT = pre_product;
            var new_top = ($(window).height() - $('#quick_view_form').height()) / 2;
            var new_left = ($(window).width() - $('#quick_view_form').width()) / 2;
            $('#quick_view_form').animate({'left' : ( 0 - $('#quick_view_form').width() - 60 ) + 'px'},500,function(){
                // Load pre product
                checkNextPreProduct();  
                $('.quick_view_loading').show();
                var uri = CURRENT_PRODUCT.attr('val');
                $.post('~product/quickViewProduct',{ uri : uri },function(data){    
                    $('#quick_view_form .content_form').html(data);
                    $('#quick_view_form .content_form img').load(function(){
                        $('.quick_view_loading').fadeOut(1000);
                    });
                });
                $('#quick_view_form').css({'top' : (- $('#quick_view_form').height() -20) + 'px', 'left' : new_left + 'px'});
                $('#quick_view_form').animate({'top' : new_top + 'px'});
            });
        }
    });

    // Su kien click vao product item
    $('.product_content').on('click','.hightlight',function(event){
        var productUri = $(this).closest('.item').attr('val');
        var dis = $(this);
        var parent = $(this).closest('.item');

        if(parent.hasClass('item_hightlight')){
            $.post('~product/removeHightLightProduct',{productUri : productUri},function(data){
                dis.closest('.item').removeClass('item_hightlight');
                dis.removeClass('active_star');
                if(dis.closest('.item').hasClass('default_product_layout')
                    || dis.closest('.item').hasClass('default_hight_light_product_layout')){
                    $('.item').css('margin','0 -1px 0 0');
                }
                else{
                    $('.item').css('margin','0px');
                }     
                $.sortProduct();
            }); 
        }
        else{
            $.post('~product/hightLightProduct',{productUri : productUri},function(data){
                dis.closest('.item').addClass('item_hightlight');
                dis.addClass('active_star');
                if(dis.closest('.item').hasClass('default_product_layout')
                    || dis.closest('.item').hasClass('default_hight_light_product_layout')){
                    $('.item').css('margin','0 -1px 0 0');
                }
                else{
                    $('.item').css('margin','0px');
                } 
                $.sortProduct();
            });
        }     
    });

    // Function sort item of product
    $.sortProduct();

    $('#my_alert_box').dialog({
        'autoOpen':false,
        'width':400,
        'height':200,
        'resizable':false,
        'modal':true,
        'title' : 'con heo con',
    });
    $('#form_page').dialog({
        'autoOpen':false,
        'width':1000,
        'height':500,
        'resizable':false,
        'modal':true,
        'dialogClass':'fixed-dialog',
    });

    $('#form_setting').dialog({
        'title' : 'SETTING',
        'autoOpen':false,
        'width':1000,
        'height':500,
        'resizable':false,
        'modal':true,
        'dialogClass':'fixed-dialog',
    });
    //Show form setting
    $('#bt_setting_option').click(function(event){
        $('#form_setting').dialog('open');
    });

    // Click vao nut dang san pham o menu ben trai
    $('#bt_add_product_form').click(function(event){
        if(event.which != 2){
            $.loadPage("~product/dangsp",'ĐĂNG SẢN PHẨM MỚI');
            event.preventDefault();
            return false;
        }
    });

    // Delay time to search
    var quickSearchTime = null;
    function quickSearch(){
        $.post('~search/quickSearch',{keyword : $("#quick_search").val()},function(data){
            $('.quick_search_result_content').html(data);
            var count = $('.quick_search_result_content').find('li').length;
            if(count > 0){
                $('#quick_search_result_panel').css('display','block');
            }
            else{
                $('#quick_search_result_panel').css('display','none');
            }
        });
    }

    // Quick search textbox change
    $("#quick_search").on("change paste keyup", function() {
        clearTimeout(quickSearchTime);
        quickSearchTime = setTimeout(quickSearch,500);
    });
    $('.quick_search_result_content').on('click','li',function(event){

    });

    $('.more_result').click(function(event){
        event.preventDefault();
        var link = $(this).find('a').attr('href') + $('#quick_search').val();
        window.location =  link;
    });

    $(document).click(function(){
        clearTimeout(quickSearchTime);
        $('#quick_search_result_panel').css('display','none');
    });

    // View image when click
    CURRENT_IMAGE = null;
    ISCLOSE = true;
    $(document).on('click','img',function(){
        if($(this).hasClass('img_copy')){
            return;
        }
        if($(this).hasClass('not_show')){
            return;
        }
        if($(this).parent().is("[href]")){
            return;
        }
        var dis = $(this);
        CURRENT_IMAGE = $(this);
        $img = $('<img/>');
        $img.addClass('img_copy');
        var factWidth = 0;
        var factHeight = 0;
        $img.css('cursor','move');
        var top = $(this).offset().top - $(document).scrollTop();
        var left = $(this).offset().left;
        var height = $(this).height();
        var width = $(this).width();    
        var src = $(this).attr('src');
        $img.load(function(){
            factWidth = this.width;
            factHeight = this.height;
            if(factHeight > $(window).height()){
                factHeight = $(window).height();
                factWidth = factHeight*this.width/this.height;
            }
            $img.css({top : top + 'px' , left : left + 'px', width : width + 'px', height : height + 'px'});
            $img.css('position','fixed');
            $img.css('z-index','999999');
            $('body').append($img);
            $('.popup_bg').fadeIn();
            var new_top = ($(window).height() - factHeight) / 2;
            var new_left = ($(window).width() - factWidth) / 2;
            $img.animate({top : new_top + 'px', left : new_left + 'px', width : factWidth +'px' , height : factHeight + 'px'},500);
        }).attr('src',src);
    });

    // Draggable image to next or pre image
    $(document).on('mouseover','.img_copy',function(){
        if (!$(this).data("init")) {
            $(this).data("init", true).draggable({ 
                axis: "x" ,
                cursor: "move",
                stop: function( event, ui ) {
                    var width = $(window).width();
                    if(ui.position.left + $(this).width()/2 > width / 2){
                        // Find next image
                        var bFind = true;
                        var nextImage = CURRENT_IMAGE.next('img');
                        if(nextImage.length == 0 || nextImage.parent().is("[href]")){
                            nextImage = CURRENT_IMAGE.parent().next().find('img');
                            if(nextImage.length == 0 || nextImage.parent().is("[href]")){
                                bFind = false;
                            }
                        }
                        if(bFind){
                            CURRENT_IMAGE = nextImage;
                            $(this).animate({'left' : (width + 20) + 'px',})
                            $nImg = $('<img/>');
                            $nImg.addClass('img_copy');
                            $nImg.css('cursor','move');
                            var link = nextImage.attr('src');
                            $nImg.load(function(){
                                var factWidth = this.width;
                                var factHeight = this.height;
                                if(factHeight > $(window).height()){
                                    factHeight = $(window).height();
                                    factWidth = factHeight*this.width/this.height;
                                }
                                var new_top = ($(window).height() - factHeight) / 2;
                                var new_left = ($(window).width() - factWidth) / 2;
                                $nImg.css({top : new_top + 'px' , left : (0 - factWidth) + 'px', width : factWidth + 'px', height : factHeight + 'px'});
                                $nImg.css('position','fixed');
                                $nImg.css('z-index','999999');
                                $('body').append($nImg);
                                $nImg.animate({left : new_left + 'px'},500);
                            }).attr('src',link);
                        }
                        else{
                            $(this).animate({'left' : ((width - $(this).width()) / 2) + 'px',})
                        }
                    }  
                    else{
                        // Prev image Slider, Find next image
                        var bFind = true;
                        var prevImage = CURRENT_IMAGE.prev('img');
                        if(prevImage.length == 0 || prevImage.parent().is("[href]")){
                            prevImage = CURRENT_IMAGE.parent().prev().find('img');
                            if(prevImage.length == 0 || prevImage.parent().is("[href]")){
                                bFind = false;
                            }
                        }
                        if(bFind){
                            $(this).animate({'left' : (0 - $(this).width() - 20) + 'px',})
                            CURRENT_IMAGE = prevImage;
                            $nImg = $('<img/>');
                            $nImg.addClass('img_copy');
                            $nImg.css('cursor','move');
                            var link = prevImage.attr('src');
                            $nImg.load(function(){
                                var factWidth = this.width;
                                var factHeight = this.height;
                                if(factHeight > $(window).height()){
                                    factHeight = $(window).height();
                                    factWidth = factHeight*this.width/this.height;
                                }
                                var new_top = ($(window).height() - factHeight) / 2;
                                var new_left = ($(window).width() - factWidth) / 2;
                                $nImg.css({top : new_top + 'px' , left : ($(window).width() + 20) + 'px', width : factWidth + 'px', height : factHeight + 'px'});
                                $nImg.css('position','fixed');
                                $nImg.css('z-index','999999');
                                $('body').append($nImg);
                                $nImg.animate({left : new_left + 'px'},500);
                            }).attr('src',link);
                        }
                        else{
                            $(this).animate({'left' : ((width - $(this).width()) / 2) + 'px',})
                        }
                    }
                },
            });
        }
    });
    $('.popup_bg').click(function(){
        $('.img_copy').fadeOut(400,function(){
            $(this).remove();
        });
        if(!ISCLOSE){
            return;
        }
        $(this).fadeOut(); 
    });

    // Event Like button
    $(document).on('click','#heart',function(){
        var hear_effect = $(this).find('.heart_effect');
        var uri = $(this).find('input').val();
        if(hear_effect.hasClass('hear_active')){
            $.post('~product/dislikeProduct',{uri : uri},function(data){
                if(data.indexOf('FALSE') != -1){
                    return;
                }
                var count = parseInt($('#heart p').text());
                $('#heart p').text(count - 1);
                hear_effect.removeClass('hear_active');
            });
        }
        else{
            $.post('~product/addLikeUser',{uri : uri},function(data){
                if(data.indexOf('FALSE') != -1){
                    return;
                }
                var count = parseInt($('#heart p').text());
                $('#heart p').text(count + 1);
                hear_effect.addClass('hear_active');
            });
        }
    });

    // Lien lac voi nguoi dang
    $(document).on('click','#bt_contact',function(){
        $.creatScreenChat($(this).attr('val')); 
        $('.message_area').addClass('on_top');
    });

    // Show Susgestion for User
    /*
    setTimeout(function(){
        if($('#category_suggestion').length == 0){
            return;
        }
        var width = $(window).width();
        var height = $(window).height();
        $('#category_suggestion').css('left', ( width + 50) + 'px');
        $('#category_suggestion').css('top', ((height - $('#category_suggestion').height()) / 2) + 'px');
        $('#category_suggestion').css('display','block');
        $('#category_suggestion .suggestion_content').load('~category/getCategorySuggetsion',function(){
            $('.popup_bg').fadeIn();
            ISCLOSE = false;
            $('#category_suggestion').css('left', ((width - $('#category_suggestion').width()) /2 ) + 'px');
        });
        },3000);
    */
    
    $('#category_suggestion .next_suggestion').click(function(){
        var width = $(window).width();
        $('#category_suggestion').css('left', (0 - width -50) + 'px');
        $('.popup_bg').fadeOut(1000);
        if(iCategorySuggestionSelect > 0){
            setTimeout(function(){
                $('#list_menufacturer_suggestion').css({'bottom' : (0 - $('#list_menufacturer_suggestion').height() - 20) + 'px'});
                $('#list_menufacturer_suggestion').css('display','block');
                $('#list_menufacturer_suggestion .suggestion_content').load('~category/loadMenufacturerSuggestion',function(){
                    $('#list_menufacturer_suggestion').css('bottom',(0 - $('#list_menufacturer_suggestion').height() - 20) + 'px');
                    $('#list_menufacturer_suggestion').animate({'bottom' : '0px'});
                });
                },3000);
        }
    });

    var iCategorySuggestionSelect = 1;
    $('#category_suggestion').on('click','.suggetion_category_item',function(){
        var categoryUri = $(this).attr('val');
        var categoryName = $(this).find('.category_name').text();
        var dis = $(this);
        $.post('~category/addCategorySuggestion',{categoryUri : categoryUri, categoryName : categoryName},function(data){
            if(data.indexOf('OK') != -1){
                iCategorySuggestionSelect++;
                dis.css({'width' : '0px'});
                setTimeout(function(){dis.remove();},600);
            }
        });
    });
    $('.close_suggestion').click(function(){
        var width = $(window).width();
        $(this).closest('.suggestion_item').css('left', (0 - width -50) + 'px');
        ISCLOSE = true;
        if(ISCLOSE){
            $('.popup_bg').fadeOut(2000);
        }
    });
    $('.close_menufacturer_suggestion').click(function(){
        $('#list_menufacturer_suggestion').animate({'bottom' : (0 - $('#list_menufacturer_suggestion').height() - 20) + 'px'});
    });

    // Add Menufacturer Suggestion
    $('#list_menufacturer_suggestion').on('click','li',function(){
        var menufacturerUri = $(this).attr('val');
        var menufacturerName = $(this).text();
        var dis = $(this);
        $.post('~category/addMenufacturerSuggestion',{menufacturerUri : menufacturerUri, menufacturerName : menufacturerName},function(data){
            if(data.indexOf('OK') != -1){
                dis.fadeOut(500,function(){
                    dis.remove();
                });
            }
        });
    });
});

// Function load page into popup
CURRENT_CELL = null;
(function( $ ){
    $.editProperty = function(data,element,event){
        if(!$('#form_edit_property').is(':hover')){
            event.stopPropagation();
        }
        if(element.find('#form_edit_property').length != 0){
            if($('#form_edit_property').css('display') == 'none'){
                $('#form_edit_property').css('display','block');
            }
            return;
        }

        var option = data.split('|');
        var bEdit = false;
        if(option[0] == 'text'){
            bEdit = true;
            $('.form_edit_content').html('<input class="prop_val" type="text" value="' + element.text() + '">');
        }
        else if(option[0] == 'longtext'){
            bEdit = true;
            $('.form_edit_content').html('<textarea class="prop_val">' + element.text() + '</textarea>');
        }
        else if(option[0] == 'list'){
            bEdit = true;
            var div = $('<div/>');
            div.addClass('custom_combobox');
            div.html($('#' + option[1]).closest('.custom_combobox').html());
            $('.form_edit_content').html('');
            $('.form_edit_content').append(div);
            $('.form_edit_content .custom_combobox_title').val(element.text());
        }
        if(bEdit){
            $('#bt_update_property').attr('data',data);
            element.append($('#form_edit_property'));
            $('#form_edit_property').css('display','block');
        }
    }
    // Replace alert basic
    $.alertBox = function($title, $content){
        $('#my_alert_box').prev().find('.ui-dialog-title').text($title);
        $('#my_alert_box').html($content);
        $('#my_alert_box').dialog('open');
    }

    // Function load page into popup
    $.loadPage = function($url,$title) {
        $('#form_page').prev().find('.ui-dialog-title').text($title);
        $('#form_page .content').html('');
        $('#form_page .page_loading').show();
        $('#form_page .content').hide();
        $('#form_page').dialog('open');
        $.post($url,{isPage : 'true'} , function(data){      
            $('#form_page .content').html(data);
            $('#form_page .content').fadeIn();
            $('#form_page .page_loading').fadeOut();
        });
    }; 
    // Function load image from URL
    $.loadImg = function($file,$sector) {
        var f = $file;
        var reader = new FileReader();

        if (!f.type.match('image.*')) {
            alert("The selected file does not appear to be an image.");
            return;
        }
        reader.onload = function (e) {
            var img = $('<img/>');
            img.attr("src", e.target.result).load(function () {
                $($sector).attr("src",e.target.result);
            });

        };
        reader.readAsDataURL(f);
    }; 

    // FUNCTION sort product item
    $.sortProduct = function(){
        var itemActives = $('.product_content').find('.item_hightlight');
        var parentWidth = $('.product_content').width();
        var itemHeight = 220;
        var itemWidth = 220;
        itemActives.each(function(){
            if($(this).position().left == 0){
                // Kiem tra neu doi tuong phia truoc rong
                var pre = $(this).prev();
                if(pre.length > 0){
                    if(pre.css('margin-left') == '0px' && pre.css('margin-top') == '0px' && pre.position().left + pre.outerWidth() < parentWidth){
                        var nextAll = $(this).nextAll('.item').not('.item_hightlight');
                        if(nextAll.length > 0){
                            var next = nextAll.eq(0);
                            var marginTop = pre.position().top - next.position().top;
                            var marginLeft = pre.position().left + pre.outerWidth() - next.position().left;
                            next.css({'margin-left': marginLeft + 'px' , 'margin-top': marginTop + 'px'});
                        }
                    }
                }
            }
        });
    };
})( jQuery );